<?php


namespace App\Models\ProductCenter\Models;


use App\Models\ProductCenter\ProductModel;
use Illuminate\Support\Facades\Cache;

class SpuModel extends ProductModel
{
    const CACHE_KEY = 'product:v1:page:';
    const INFO_KEY = 'product:v1:info:id:';
    public $table = 'product_spu';
    public $fillable = [
        'spu', //varchar(32) CHARACTER NOT NULL DEFAULT '',
        'name', //varchar(128) CHARACTER NOT NULL DEFAULT '' COMMENT '中文名',
        'en_name', //varchar(128) CHARACTER NOT NULL DEFAULT '' COMMENT '英文名',
        'image_url',
        'category_id', //int NOT NULL DEFAULT '0' COMMENT '所属品类id',
        'brand_id', //int NOT NULL DEFAULT '0' COMMENT '品牌id',
//        'create_time', //datetime DEFAULT NULL,
//        'update_time', //datetime DEFAULT NULL,
        'create_user', //varchar(64) COLLATE utf8mb4_general_ci NOT NULL DEFAULT '',
        'create_user_uuid', //varchar(64) COLLATE utf8mb4_general_ci NOT NULL DEFAULT '',
        'attribute',// json DEFAULT NULL COMMENT '属性字段',
        'describe',// text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci,
    ];

    public $casts = [
        'attribute' => 'array'
    ];

    public function sku()
    {
        return $this->hasMany(SkuModel::class, 'spu_id', 'id');
    }

    public function brand()
    {
        return $this
            ->belongsTo(BrandModel::class, 'brand_id', 'id')
            ->withDefault();
    }

    public function category()
    {
        return $this
            ->belongsTo(CategoryModel::class, 'category_id', 'id')
            ->withDefault();
    }

    public function getSpuInfo($where)
    {
        $res = $this->handlecOndition($where)
            ->with([
                'brand',
                'sku',
                'sku.skuInfo',
                'sku.skuInfo.size',
            ])
            ->first();

        if (is_null($res))
            throwError();

        $res = $res->toArray();
        foreach ($res['sku'] as &$v) {
            foreach ($v['sku_info'] as $j) {
                $v['size_select'][] = $j['size_id'];
            }
        }

        return $res;
    }

    public function getSpuList($data)
    {
        $where = [];
        is_real_exists(@$data['name']) && $where['name'] = ['like', '%'.$data['name'].'%'];
        is_real_exists(@$data['spu']) && $where['spu'] = ['like', '%'.$data['spu'].'%'];
        is_real_exists(@$data['category_id']) && $where['category_id'] = $data['category_id'];
        is_real_exists(@$data['create_user_uuid']) && $where['create_user_uuid'] = $data['create_user_uuid'];
        is_real_exists(@$data['brand_id']) && $where['brand_id'] = $data['brand_id'];
        is_real_exists(@$data['status']) && $where['status'] = $data['status'];
        is_real_exists(@$data['create_time']) && $where['create_time'] = ['between', $data['create_time']];

        $spu = $this->handlecOndition($where)
            ->with([
                'brand:id,name',
                'category:id,name',
                'sku',
                'sku.skuInfo',
            ]);

        if (isset($data['sku'])) {
            $spu->whereHas('sku', function ($query) use ($data) {
               $query->where('sku', 'like', '%'.$data['sku'].'%');
            });
        }

        if (isset($data['price'])) {
            $spu->whereHas('sku.skuInfo', function ($query) use ($data) {
               $query->whereBetween('price', $data['price']);
            });
        }

        return $spu
            ->orderBy('sort', 'desc')
            ->paginate(config('pageSize'));
    }

    /*
    protected static function boot()
    {
        parent::boot();

        static::deleting(function($spu) {
            $ids = $spu->sku()->pluck('id');
            $sku = new SkuModel();
            $skuInfo = new SkuInfoModel();
            foreach ($ids as $v) {
                $where['id'] = $v;
                $skuInfo->handleCondition(['sku_id' => $v])->delete();
                $sku->handleCondition($where)->first()->delete();
            }
        });
    }
    */

    public function getProductListV1($data)
    {
        $where = [];
        is_real_exists(@$data['name']) && $where['name'] = ['like', '%'.$data['name'].'%'];
        is_real_exists(@$data['brand_id']) && $where['brand_id'] = $data['brand_id'];
        is_real_exists(@$data['category_id']) && $where['category_id'] = $data['category_id'];

        if (empty($where)) {
            if (Cache::has(self::CACHE_KEY.config('page'))) {
                dd(1);
                return json_decode(Cache::get(self::CACHE_KEY.config('page')), true);
            }
        }

        $spuField = [
            'id',
            'spu',
            'name',
            'en_name',
            'category_id',
            'brand_id',
            'image_url',
            'create_time',
            'view_num',
            'sale_num',
            'attribute',
            'describe'
        ];

        $res = $this
            ->handleCondition($where)
            ->with([
                'brand:id,name',
                'category:id,name',
                'sku' => function ($query) {
                    $where = [
                        'status' => self::TRUE,
                        'is_delete' => self::False
                    ];
                    $fieldRaw = 'id,spu_id,spu,sku,name,image_url,price,newest_price,stock,content,size_type,sale_num';
                    $query->where($where)
                        ->selectRaw($fieldRaw);
                },
//                'sku.skuInfo:sku_id,size_id',
//                'sku.skuInfo.size:id,label,value',
            ]);

        if (is_real_exists(@$data['sku'])) {
            $res->whereHas('sku', function ($query) use ($data) {
                $query->where('sku', $data['sku']);
            });
        }
        $res = $res
            ->paginate(config('pageSize'), $spuField)
            ->toArray();

        if (empty($where)) {
            Cache::set(self::CACHE_KEY.config('page'), json_encode($res), 3600*24);
        }

        return $res;
    }

    public function getProductInfoV1($data)
    {
        $key = self::INFO_KEY.$data['id'];
        if (Cache::has($key)) {
            return json_decode(Cache::get($key), true);
        }
        $where['id'] = $data['id'];

        $spu = $this
            ->handleCondition($where)
            ->with([
                'brand:id,name',
                'category:id,name',
                'sku' => function ($query) {
                    $where = [
                        'status' => self::TRUE,
                        'is_delete' => self::False
                    ];
                    $fieldRaw = 'id,spu_id,spu,sku,name,image_url,price,newest_price,stock,content,size_type,sale_num';
                    $query->where($where)
                        ->selectRaw($fieldRaw);
                },
                'sku.skuInfo:sku_id,size_id',
                'sku.skuInfo.size:id,label,value',
            ])
            ->first();

        if (is_null($spu)) {
            throwError();
        }

        $max = 0.00;
        $max_new = 0.00;
        $min =  0.00;
        $min_new = 0.00;
        foreach ($spu->sku as $v) {
            $max = $v->price > $max ? $v->price : $max;
            $min = $v->price < $min ? $v->price : $max;
            $max_new = $v->newest_price > $max ? $v->newest_price : $max;
            $min_new = $v->newest_price < $min ? $v->newest_price : $max;
        }
        $spu->price = $min.'--'.$max;
        $spu->newest_price = $min_new.'--'.$max_new;

        Cache::set($key, json_encode($spu->toArray()), 3600*24);


        return $spu;
    }
}
